<?php
class VES_VendorsWarehouse_Warehouse_AddressController extends VES_Vendors_Controller_Action
{
    private  $address_filter=array(
        'sender_name'=>'require',
    );
    
    private $details_filter=array(
        'sender_phone'=>"",        
        'sender_address'=>'require',
        'sender_phone'=>"",
        'sender_country'=>"",
        'sender_province_id'=>"",
        'sender_city'=>"",
        'sender_email'=>"",
        'sender_contact'=>'require',
    );
    public function indexAction()
    {
//         $Collection = Mage::getModel('vendorswarehouse/address')->getCollection();
//        $Collection->getSelect()
//         ->columns(array("number"=>new Zend_Db_Expr('MAX(number)')));
        
    
//         print_r($Collection->getData());
   
    }
    public function saveAction(){
        $wid = $this->getRequest()->getParam("id");
        if(!$wid){
            $this->_redirect("*/*/");
            return ;
        }
        $this->loadLayout();
        $vendor_id=Mage::getSingleton('vendors/session')->getId();
        $collection = Mage::getModel('vendorswarehouse/address')->getCollection()
        ->addFieldToFilter("vendor_id",array("eq"=>$vendor_id))
        ->addFieldToFilter("entity_id",array("eq"=>$wid));
        $collection->getSelect()->join(array('warehouse_detail' => 'ves_vendor_warehouse_details'), 'warehouse_detail.wid = entity_id');
       Mage::register('warehouse_detailsData',$collection);
       $this->getLayout()->getBlock('content')->append(
           $this->getLayout()->createBlock('vendorswarehouse/address')
           );
        $this->renderLayout();
    }
    
    public  function savePostAction($ajaxData=array()){
        if(!empty($ajaxData)){
            $postData =$ajaxData;
        }else{
            $postData = $this->getRequest()->getPost();
        }
      
//        foreach($postData as $key=>$value)$details_model->setData($key,$value);

       try{
           $getId=$this->getRequest()->getParam("id");
           if($getId){
               $address_model =  Mage::getModel("vendorswarehouse/address")->load($getId);
           }else{
               $address_model =  Mage::getModel("vendorswarehouse/address");
           }
          $VendorId = Mage::getSingleton('vendors/session')->getId();
          $vendor = Mage::getSingleton('vendors/session')->getVendor();
          $address_model-> setVendorId($VendorId);
           $address_model
           ->setSenderName($postData['sender_name'])
           ->setStatus($postData['status']);
           ;
           
           if(!$getId){
            $head = substr($VendorId,0,strpos($VendorId,"S"));
            //设置仓库编码
            $Collection = Mage::getModel('vendorswarehouse/address')->getCollection()
            ->addFieldToFilter("sender_zip_code",array("like"=>$head."%"));

            $Collection->getSelect()
            ->columns(array("sender_zip_code"=>new Zend_Db_Expr('MAX(sender_zip_code)')));
            $maxCode= $Collection->getFirstItem()->getData("sender_zip_code");
            if(empty($maxCode)){
                $startnum = strpos($vendor->getVendorId(),"S");
                if($startnum ==false){
                    $this->_critical("仓库编码生成失败",400);
                }
                $laststr = substr($VendorId,$startnum+1);
                $zipCode = ($head . "SW" . $laststr);
            }else{
                $startnum = strpos($maxCode,"W");
                if($startnum ==false){
                    $this->_critical("仓库编码获取失败",400);
                }
                $laststr = (int)substr($maxCode,$startnum);
                $laststr+=1;
               if(strlen($laststr)!=5){
                   $laststr =  str_pad($laststr,5,"0",STR_PAD_LEFT);
               }
                 $zipCode = ($head . "SW" . $laststr);
            }
            $address_model->setSenderZipCode($zipCode);
          
               //如果是默认地址  则修改vendors 属性仓库编码的值
               if($postData['is_default']==1){
                  
                   $vendor->setWarehouseCode($zipCode);
                   $vendor->save();
               }
           }  
           $address_model->save();
           $addressId =$address_model->getEntityId();
           if(!$addressId) {
               throw new Exception("address details save error");
           }
        if($getId){
           $details_model =  Mage::getModel("vendorswarehouse/details")->load($getId,"wid");
           $details_model->setUpdateTime(now());
        }else{
            $details_model = Mage::getModel("vendorswarehouse/details");
        }
       foreach($this->details_filter as $attr => $v){
           $details_model->setData($attr,$postData[$attr]);
       }
       $details_model->setWid($addressId);
       $details_model->save();
       if(empty($ajaxData)){
           $this->_redirect('*/warehouse_address/created',array(
               '_current'   => true));
          }
       }catch (Exception $e) {
        	Mage::getSingleton('vendors/session')->addError($e->getMessage());
        	Mage::log($e->getMessage());
        	Mage::getSingleton('vendors/session')->setFormData($postData);
        	if(empty($ajaxData)){
        	  $this->_redirect('*/*/');
        	}
        	return;
        }
    }
    public function createdAction()
    {
        $this->_getSession()->addNotice(
            Mage::helper('vendorswarehouse')->__('Please click on the Close Window button if it is not closed automatically.')
            );
        $this->loadLayout();
        $this->_addContent(
            $this->getLayout()->createBlock('vendorswarehouse/address_created')
            );
        $this->renderLayout();
    }
    
    public function quickcreateAction(){
        if (!$this->getRequest()->isAjax()) {
            $this->_forward('noRoute');
            return;
        } 
        try {
            $ajaxData = $this->getRequest()->getPost();
            $result = array();
            $check_filter = array_merge($this->details_filter,$this->address_filter);
            //validate
            foreach($ajaxData as $key=>$val){
                if($check_filter[$key]=="require"){
                    if($val==""){
                      throw Mage::exception('Mage_Core',$key." must be set");
                    }
                }
            }
            //利用savePost方法保存数据
            $this->savePostAction($ajaxData);
            $this->_getSession()->addSuccess(Mage::helper('vendorswarehouse')->__('Warehouse Address has been saved'));
            $this->_initLayoutMessages('adminhtml/session');
            $result['messages']  = $this->getLayout()->getMessagesBlock()->getGroupedHtml();
        } catch (Mage_Core_Exception $e) {
                $result['error'] = $e->getMessage();
        } catch (Exception $e) {
                $result['error'] = $e->getMessage();
//             $this->_getSession()->addError(Mage::helper('vendorswarehouse')->__($e->getMessage()));
            
        }
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
    }
    /**
     * Get address grid
     *
     */
    public function addressgridAction()
    {
        $this->loadLayout(false);
        $this->renderLayout();
    }
    public function validateAction(){
        $response = new Varien_Object();
        $response->setError(false);
        
        try {
            $postData = $this->getRequest()->getPost();
            $check_filter = array_merge($this->details_filter,$this->address_filter);
                foreach($postData as $key=>$val){
                   if($check_filter[$key]=="require"){
                       if($val==""){
                           throw new Exception($key." must be set");
                       }
                   }
                } 
        } catch (Exception $e) {
            $response->setError(true);
            $response->setMessage($e->getMessage());
        }
       
        $this->getResponse()->setBody($response->toJson());
    }
}